#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<error.h>

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("usage: client <IPAddress>！\n");
        exit(EXIT_FAILURE);
    }

    char *serv_ip = argv[1]; 
    int sockfd, addr_len, buf_len;
    struct sockaddr_in servaddr;
    addr_len = sizeof(servaddr);
    char buffer[256];
    buf_len = sizeof(buffer);

    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        perror("fail to socket: ");
        exit(EXIT_FAILURE);
    }

    bzero(&servaddr, addr_len);

    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(3000);
    servaddr.sin_addr.s_addr = inet_addr(serv_ip);
    /* if((inet_aton(serv_ip, &(servaddr.sin_addr))) == 0 )
    {
        perror("fail to inet_aton:");
        exit(EXIT_FAILURE);
    } */
    
    while(1)
    {
        bzero(buffer, buf_len);
        printf("Please enter a string to send to server: \n");
        read(0, buffer, buf_len); // 0 -- 文件描述， 表示的是终端的输入描述符

        if((sendto(sockfd, buffer, buf_len, 0, (struct sockaddr *)&servaddr, addr_len)) == -1)
        {
            perror("fail to sendto: ");
            exit(EXIT_FAILURE);
        }

        if((recvfrom(sockfd, buffer, buf_len, 0, (struct sockaddr*)&servaddr, &addr_len)) == -1)
        {
            perror("fail to recvfrom: ");
            exit(EXIT_FAILURE);
        }

        printf("recerve from server: %s\n", buffer);
    }

    return 0;
}